package com.tcl.hystrix.config;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.tcl.api.response.UserResponse;
import com.tcl.hystrix.feign.UserServiceFeignClient02;

/**
 * @Author liuf
 * @Date 2020/12/17 16:18
 * @Description
 */
public class ExecuteFeignHystrix extends HystrixCommand<UserResponse> {

    private UserServiceFeignClient02 userServiceFeignClient02;

    private Integer userId;

    public ExecuteFeignHystrix(UserServiceFeignClient02 userServiceFeignClient02, Integer userId) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("orderService"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("queryByOrderId"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        //至少有10个请求，熔断器才进行错误率的计算
                        .withCircuitBreakerRequestVolumeThreshold(10)
                        //熔断器中断请求5秒后会进入半打开状态,放部分流量过去重试
                        .withCircuitBreakerSleepWindowInMilliseconds(5000)
                        //错误率达到50开启熔断保护
                        .withCircuitBreakerErrorThresholdPercentage(50)
                        .withFallbackEnabled(true)
                        .withExecutionTimeoutInMilliseconds(1000)
                        //最大并发请求量
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                ));
        this.userServiceFeignClient02 = userServiceFeignClient02;
        this.userId = userId;
    }


    @Override
    protected UserResponse run() throws Exception {
        return userServiceFeignClient02.get(userId);
    }


    @Override
    protected UserResponse getFallback() {
        UserResponse userResponse = new UserResponse();
        userResponse.setId(1);
        userResponse.setName("服务降级");
        return userResponse;
    }
}
